package com.mall.biz.user;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mall.client.commkey.CommKeyService;
import com.mall.client.user.SessService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserService;
import com.mall.common.Consts.PassJiaMi;
import com.mall.common.util.MD5Util;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.common.util.token.TokenUtils;
import com.mall.constant.PropertiesKey;
import com.mall.enums.RegionEnum;
import com.mall.pojo.Commkey;
import com.mall.pojo.Sess;
import com.mall.pojo.User;
import com.mall.pojo.UserExample;
import com.mall.pojo.UserExample.Criteria;
import com.mall.pojo.UserExtended;
import com.mall.vo.user.UserVO;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.WebUtil;

@Service
public class UserBizImpl {

	private Logger log = LoggerFactory.getLogger(UserBizImpl.class);

	@Autowired
	private UserService userService;
	@Autowired
	private PropertiesConfigure propertiesConfigure;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private SessService sessService;
	@Autowired
	private CommKeyService commKeyService;

	public UserVO login(String phone, String pass, Integer onlyKey) {
		User user = this.userService.getUserByPhone(phone, onlyKey);
		if (user == null) {
			return null;
		}
		UserExample userExample = new UserExample();
		Criteria criteria = userExample.createCriteria();
		criteria.andPhoneEqualTo(phone.trim());
		criteria.andPasswordEqualTo(MD5Util.GetMD5Code(pass, phone + "", PassJiaMi.MD5JIAYAN));
		//criteria.andStatusNotEqualTo(Short.parseShort("0"));// 新注册的用户没通过验证码验证
		criteria.andCommOnlyKeyEqualTo(onlyKey);
		List<User> userList = this.userService.getUserByExample(userExample);
		if (userList == null || userList.size() <= 0) {
			return null;
		}

		return this.getUserVOByUserId(userList.get(0).getId());
	}

	public UserVO getUserVOByUserId(Long userId) {
		if (userId == null || userId <= 0) {
			return null;
		}
		User user = this.userService.getUserByUserId(userId);
		String token = TokenUtils.getToken(userId, user.getPassword(), new Date());
		UserExtended userExtended = userExtendedService.getUserExtendByUserId(userId);
		UserVO userVO = new UserVO();
		userVO.setToken(token);
		userVO.setUser(user);
		userVO.setUserExtended(userExtended);
		userVO.setImgBeiginUrl(propertiesConfigure.getProperties(PropertiesKey.userfilepath));

		return userVO;

	}

	/**
	 * 判断更新阿里百川的deviceToken
	 * 
	 * @param userVO
	 * @param deviceToken
	 * @return
	 */
	public Boolean updateDeviceToken(UserVO userVO, String deviceToken) {
		if (StringUtils.isNotBlank(deviceToken)) {
			UserExtended userExtended = userVO.getUserExtended();
			userExtended.setDeviceToken(deviceToken);
			userExtended.setGmtCreate(new Date());
			this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		}
		return true;
	}

	public Boolean updateOrInsertSess(HttpServletRequest request, HttpServletResponse response, UserVO userVO,
			Integer onlyKey) {
		User loginUser = userVO.getUser();
		String juid = WebUtil.getUserCookieValue(request);
		boolean boolInsert = false;
		List<Sess> sessList = null;
		sessList = this.sessService.getListBySessionKey(juid, onlyKey);
		if (sessList == null || sessList.isEmpty()) {
			boolInsert = true;
		}
		Sess sess = null;
		if (boolInsert) {
			sess = new Sess();
			List<Commkey> commKeyList = this.commKeyService.getComKeyByCommOnlyKey(onlyKey);
			sess.setCommOnlyKey(onlyKey);
			if (!CollectionUtils.isEmpty(commKeyList)) {
				sess.setProvinceId(commKeyService.getRegionByList(RegionEnum.PROVINCE.getCode(), commKeyList));
				sess.setCityId(commKeyService.getRegionByList(RegionEnum.CITY.getCode(), commKeyList));
				sess.setAreaId(commKeyService.getRegionByList(RegionEnum.AREA.getCode(), commKeyList));
			}

			sess.setSesskey(juid);
			sess.setUid(loginUser.getId());
			sess.setIp(HttpUtil.getIpAddress(request));
			int insert = this.sessService.insertSess(sess);
			if (insert <= 0) {
				log.error("insert Sess error." + loginUser.getId() + "--time=" + System.currentTimeMillis());
				WebUtil.setCurrentUserSessionAndCookies(request, response, loginUser);
				return false;
			}
		} else {
			sess = sessList.get(0);
			sess.setUid(loginUser.getId());
			sess.setIp(HttpUtil.getIpAddress(request));
			int update = this.sessService.updateSess(sess);
			if (update <= 0) {
				log.error("update Sess error." + loginUser.getId() + "--time=" + System.currentTimeMillis());
				WebUtil.setCurrentUserSessionAndCookies(request, response, loginUser);
				return false;
			}
		}
		userVO.setSessKey(sess.getSesskey());
		WebUtil.setCurrentUserSessionAndCookiesFromLoginAndRegister(request, response,juid, loginUser);
		return true;
	}

	/**
	 * 更新用户名
	 * 
	 * @param user
	 * @param userName
	 */

	public void updateUserNameByUser(User user, String userName) {
		if (StringUtils.isNotBlank(userName)) {
			user.setUserName(userName);
			user.setNameAndPhone(user.getPhone()+userName);
		} else {
			return;
		}
		user.setGmtModify(new Date());
		this.userService.modifytUserByExample(user, user.getId());
	}

	/**
	 * 修改用户的性别
	 * 
	 * @param user
	 * @param sex
	 */
	public void updateUserSexByUser(User user, String sex) {
		if (StringUtils.isNotBlank(sex)) {
			Short sexInt = Short.parseShort(sex);
			user.setSex(sexInt);
			user.setGmtModify(new Date());
		} else {
			return;
		}
		this.userService.modifytUserByExample(user, user.getId());

	}

	/**
	 * 修改用户头像路径
	 * 
	 * @param user
	 * @param imgFilePath
	 */
	public void updatePortraitByUser(User user, String imgFilePath) {
		if (StringUtils.isNotBlank(imgFilePath)) {
			user.setPortrait(imgFilePath);
			user.setGmtModify(new Date());
		} else {
			return;
		}
		this.userService.modifytUserByExample(user, user.getId());

	}

}
